//
//  WJCommonUtils.m
//  ChiShaNe
//
//  Created by 王军 on 16/3/25.
//  Copyright © 2016年 王军. All rights reserved.
//

#import "WJCommonUtils.h"
#import <CommonCrypto/CommonDigest.h>
#import <sys/stat.h>
#import <sys/types.h>
#import <dlfcn.h>
#include <objc/objc.h>
#include <objc/runtime.h>
#include <stdio.h>
#include <string.h>
#import <mach-o/dyld.h>
#import <AVFoundation/AVFoundation.h>
#import "UIImage+YYAdd.h"

@implementation WJCommonUtils

#pragma mark -- 字符串处理
//IOS判断字符串是否为空
+(BOOL)isBlankString:(NSString *)string
{
    if(string == nil || string == NULL)
    {
        return YES;
    }
    if([string isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)
    {
        return YES;
    }
    return NO;
}


+(NSString *)str2def:(NSString *)string def:(NSString *)def
{
    if(string == nil || string == NULL ||[string isKindOfClass:[NSNull class]])
    {
        if (def == nil)
        {
            return @"";
        }
        else
        {
            return def;
        }
    }
    return string;
}


/** 对象转换成string */
+(NSString*)obj2str:(id)obj{
    if(nil==obj ||obj == NULL){
        return @"";
    }
    if([obj isKindOfClass:NSClassFromString(@"NSNumber")]){
        return [obj stringValue];
    }else if([obj isKindOfClass:NSClassFromString(@"NSString")]){
        return obj;
    }else if([obj isKindOfClass:NSClassFromString(@"NSNull")]){
        return @"";
    }
    return obj;
}



/** 字符串是否包含另一个字符串 */
+(BOOL)string:(NSString *)str containStr:(NSString *)subStr
{
    NSRange range = [str rangeOfString:subStr];//判断字符串是否包含
    if (range.length >0)//包含
    {
        return YES;
    }
    return NO;
}

//去掉html标签
+(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}

//是否全部是数字
+(BOOL) isNumberic:(NSString *)str{
//    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[^4,\\D])|(147)|(170))\\d{8}$";
//    NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
//    return [numberTest evaluateWithObject:str];
    return [WJCommonUtils checkSpecilChar:str charSetStr:@"0123456789."];
}

//4+-+8
+(BOOL) isValidateTel:(NSString *)tel{
    if(tel.length<7){
        return NO;
    }
    if(tel.length<9){
        if ([WJCommonUtils isNumberic:tel]) {
            return YES;
        }
    }
    if (tel.length>14) {
        return NO;
    }
    NSString * telRegex = @"^(0[0-9]{2})(-)?\\d{8}$|^(0[0-9]{3}(-)?(\\d{7,8}))$";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",telRegex];
    return [telTest evaluateWithObject:tel];
}

+(BOOL) isValidateMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        return YES;
//        /**
//         * 移动号段正则表达式
//         */
//        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
//        /**
//         * 联通号段正则表达式
//         */
//        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
//        /**
//         * 电信号段正则表达式
//         */
//        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
//        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
//        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
//        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
//        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
//        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
//        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
//
//        if (isMatch1 || isMatch2 || isMatch3) {
//            return YES;
//        }else{
//            return NO;
//        }
    }
}
//邮箱
+ (BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//58.215.133.212
+ (BOOL)isValidateIPV4:(NSString *)ipStr{
    BOOL bo = [WJCommonUtils checkSpecilChar:ipStr charSetStr:@"0123456789."];
    if (!bo) {
        return  NO;
    }
    NSCharacterSet *characterSet1 = [NSCharacterSet characterSetWithCharactersInString:@"."];
    NSArray *array1 = [ipStr componentsSeparatedByCharactersInSet:characterSet1];
    if (array1.count != 4){
        return NO;
    }
    if (array1.count == 4) {
        for(NSString *string1 in array1)
        {
            if (string1.integerValue>= 0 && string1.integerValue<=255) {
                continue;
            }else{
                return NO;
            }
        }
    }
    return YES;
}


/** 字符串加密(MD5 32位 小写) */
+(NSString *)md5:(NSString *)input
{
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (int)strlen(str), result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];//
    
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}


/** 字符串是否由后面的组成 */
+(BOOL)checkSpecilChar:(NSString*)str charSetStr:(NSString *)charSetStr{
    NSCharacterSet *charset = [[NSCharacterSet characterSetWithCharactersInString:charSetStr]invertedSet];
    NSRange range = [str rangeOfCharacterFromSet:charset];
    if (range.location != NSNotFound)
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}


+(NSString *)KBMGT_float:(CGFloat )sumValue{
    //    CGFloat sumValue = mem.floatValue;
    CGFloat unitValue = 1000;
    if (sumValue >= pow(unitValue, 4)) {
        CGFloat f = sumValue/pow(unitValue, 4);
        NSString *ret = [NSString stringWithFormat:@"%.2fT",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 4) && sumValue >=  pow(unitValue, 3) ){
        CGFloat f = sumValue/pow(unitValue, 3);
        NSString *ret = [NSString stringWithFormat:@"%.2fG",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 3) && sumValue >=  pow(unitValue, 2) ){
        CGFloat f = sumValue/pow(unitValue, 2);
        NSString *ret = [NSString stringWithFormat:@"%.2fM",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 2) && sumValue >=  pow(unitValue, 1) ){
        CGFloat f = sumValue/pow(unitValue, 1);
        NSString *ret = [NSString stringWithFormat:@"%.2fK",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 1) && sumValue >=  0 ){
        CGFloat f = sumValue;
        NSString *ret = [NSString stringWithFormat:@"%.2fB",f];
        return ret;
    }
    NSString *ret = [NSString stringWithFormat:@"%.2f",sumValue];
    return ret;
}

//小数点后面不要
+(NSString *)KBMGT_float_0:(CGFloat )sumValue{
//    sumValue = 
    CGFloat unitValue = 1000;
    if (sumValue >= pow(unitValue, 4)) {
        CGFloat f = sumValue/pow(unitValue, 4);
        NSString *ret = [NSString stringWithFormat:@"%.0fT",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 4) && sumValue >=  pow(unitValue, 3) ){
        CGFloat f = sumValue/pow(unitValue, 3);
        NSString *ret = [NSString stringWithFormat:@"%.0fG",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 3) && sumValue >=  pow(unitValue, 2) ){
        CGFloat f = sumValue/pow(unitValue, 2);
        NSString *ret = [NSString stringWithFormat:@"%.0fM",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 2) && sumValue >=  pow(unitValue, 1) ){
        CGFloat f = sumValue/pow(unitValue, 1);
        NSString *ret = [NSString stringWithFormat:@"%.0fK",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 1) && sumValue >=  0 ){
        CGFloat f = sumValue;
        NSString *ret = [NSString stringWithFormat:@"%.0fB",f];
        return ret;
    }
    NSString *ret = [NSString stringWithFormat:@"%.0f?",sumValue];
    return ret;
}


//小数点后面不要
+(NSString *)KBMGT_float_1:(CGFloat )sumValue{
    CGFloat unitValue = 1000;
    if (sumValue >= pow(unitValue, 4)) {
        CGFloat f = sumValue/pow(unitValue, 4);
        NSString *ret = [NSString stringWithFormat:@"%.1fT",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 4) && sumValue >=  pow(unitValue, 3) ){
        CGFloat f = sumValue/pow(unitValue, 3);
        NSString *ret = [NSString stringWithFormat:@"%.1fG",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 3) && sumValue >=  pow(unitValue, 2) ){
        CGFloat f = sumValue/pow(unitValue, 2);
        NSString *ret = [NSString stringWithFormat:@"%.1fM",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 2) && sumValue >=  pow(unitValue, 1) ){
        CGFloat f = sumValue/pow(unitValue, 1);
        NSString *ret = [NSString stringWithFormat:@"%.1fK",f];
        return ret;
    }
    else if (sumValue <  pow(unitValue, 1) && sumValue >=  0 ){
        CGFloat f = sumValue;
        NSString *ret = [NSString stringWithFormat:@"%.1fB",f];
        return ret;
    }
    NSString *ret = [NSString stringWithFormat:@"%.1f?",sumValue];
    return ret;
}


#pragma mark -- 字符串json
//JSON.parse()和JSON.stringify()
// NSArray/NSDictionary ==> NSString/NSData
+(NSString *)JSONStringify:(id) obj{
    if ([NSJSONSerialization isValidJSONObject:obj])
    {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return @"";
}

//NSString/NSData ==> NSArray/NSDictionary
+(id)JSONParse:(id) obj{
    if(!([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSData class]]))
    {
        NSLog(@"转json对象的参数类型不正确");
        return nil;
    }
    NSData *data = nil;
    if([obj isKindOfClass:[NSString class]])
    {
        data = [obj dataUsingEncoding:NSUTF8StringEncoding];
    }
    if ([obj isKindOfClass:[NSData class]])
    {
        data = obj;
    }
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    if(error){
        NSLog(@"An error happened while deserializing the JSON data.");
    }
    return jsonObject;
}
#pragma mark -- 数据持久
+(void)saveValue:(id)v withKey:(NSString *)key{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:v forKey:key];
    [userDefaults synchronize];
}
+(id)getValueWithKey:(NSString*)key{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:key];
}
+(NSString *)getStringWithKey:(NSString*)key{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *str = (NSString *)[userDefaults objectForKey:key];
    return str;
}
+(void)saveCacheValue:(id)v withKey:(NSString *)key time:(NSInteger)t{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:v forKey:key];
    [userDefaults synchronize];
}
+(id)geCachetValueWithKey:(NSString*)key{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:key];
}

+(void)archiveKey:(NSString *)key value:(id)value{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:value];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:data forKey:key];
}

+(id)archiveGetValue:(NSString *)key{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSData *data = [user objectForKey:key];
    if([data isKindOfClass:[NSData class]]){
        id obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        return obj;
    }
    return data;
}

+(void)cleanArchiveDataWithKey:(NSString *)key{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
      [user setObject:nil forKey:key];
}


#pragma mark -- 图片

+ (UIImage *) imageFromColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
/**
 压图片质量
 
 @param image image
 @return Data
 */
+ (NSData *)zipImageWithImage:(UIImage *)image maxFileSize:(CGFloat)maxFileSize
{
    if (!image) {
        return nil;
    }
    CGFloat compression = 0.9f;
    NSData *compressedData = UIImageJPEGRepresentation(image, compression);
    // 先直接压缩一半看看
    for (int i = 0; i < 10; i++) {
        CGFloat tempCompression = compression * 0.5;
        NSData *halfData = UIImageJPEGRepresentation([[self class] compressImage:image newWidth:image.size.width*tempCompression], tempCompression);
        if([halfData length] > maxFileSize){
            compression *= 0.5;
        }
        else {
            break;
        }
    }
    while ([compressedData length] > maxFileSize) {
        compression *= 0.9;
        compressedData = UIImageJPEGRepresentation([[self class] compressImage:image newWidth:image.size.width*compression], compression);
    }
    return compressedData;
}

/**
 压图片质量
 
 @param image image
 @return Data
 */
+ (NSData *)zipImageWithImage:(UIImage *)image
{
    if (!image) {
        return nil;
    }
    CGFloat maxFileSize = 32*1024;
    CGFloat compression = 0.9f;
    NSData *compressedData = UIImageJPEGRepresentation(image, compression);
    while ([compressedData length] > maxFileSize) {
        compression *= 0.9;
        compressedData = UIImageJPEGRepresentation([[self class] compressImage:image newWidth:image.size.width*compression], compression);
    }
    return compressedData;
}

/**
 *  等比缩放本图片大小
 *
 *  @param newImageWidth 缩放后图片宽度，像素为单位
 *
 *  @return self-->(image)
 */
+ (UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth
{
    if (!image) return nil;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = newImageWidth;
    float height = image.size.height/(image.size.width/width);
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return newImage;
}


#pragma mark -- UIKit

+(void)closeKeyboard{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

/** 拿到subView所在的UIViewController */
+(UIViewController *)viewController:(UIView*)subView {
    for (UIView* next = [subView superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}
/** 移除本视图上所有的子视图 */
+(void)removeSubviews:(UIView *)view
{
    for (UIView *subView in [view subviews]) {
        [subView removeFromSuperview];
    }
}

+(CGSize)getSizeTxt:(UILabel *)lbl{
    NSString *content = lbl.text;
    UIFont *font =lbl.font;
    CGSize size =[content sizeWithAttributes:@{NSFontAttributeName:font}];
    return size;
}

+(CGFloat)valueHeight:(UILabel *)valuelbl{
    if(valuelbl == nil || [valuelbl isKindOfClass:[NSNull class]]){
        return 0;
    }
    NSString *content = valuelbl.text;
    if ([WJCommonUtils isBlankString:content]) {
        content = @"";
    }
    CGFloat contentW = valuelbl.frame.size.width;
    CGSize size = [content boundingRectWithSize:CGSizeMake(contentW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:valuelbl.font} context:nil].size;
    return size.height;
}



//拨打电话
+(void)callPhone:(NSString *)phoneNo{
    int type = 2;//1\2\3
    if (type == 1)
    {//有确认拨打
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNo];
        UIWebView * callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:callWebview];
    }
    else if (type ==2)
    {//有确认拨打
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phoneNo];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
    else if (type ==3)
    {//直接拨打出去
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNo];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}
//+(void)saveValue:(id)v withKey:(NSString *)key;
//+(id)getValueWithKey:(NSString*)key;
//+(NSString *)getStringWithKey:(NSString*)key;

//记录密码
+(void)savePassord:(NSString *)pwd withId:(NSString *)username withKey:(NSString *)keyStr{
    NSString *saveKey = [NSString stringWithFormat:@"SAVEPWD_%@_%@",keyStr,username];
    [WJCommonUtils saveValue:pwd withKey:saveKey];
}

+(NSString *)getPassordWithId:(NSString *)username withKey:(NSString *)keyStr{
    NSString *saveKey = [NSString stringWithFormat:@"SAVEPWD_%@_%@",keyStr,username];
    NSString *value = [WJCommonUtils getValueWithKey:saveKey];
    if ([WJCommonUtils isBlankString:value]) {
        value = @"";
    }
    return value;
}




//4.使用stat系列函数检测Cydia等工具
bool checkCydia(void)
{
    struct stat stat_info;
    if (0 == stat("/Applications/Cydia.app", &stat_info)) {
        NSLog(@"Device is jailbroken");
        return true;
    }
    return false;
}
//5.看看stat是不是出自系统库，有没有被攻击者换掉


int checkInject(void)
{
//    int ret ;
//    Dl_info dylib_info;
//    int (*func_stat)(const char *, struct stat *) = stat;
//    dladdr(func_stat, &dylib_info);
    
    
//    if ((ret = dladdr(func_stat, &dylib_info))) {
//        NSLog(@"lib :%s", dylib_info.dli_fname);
//    }
    return 0;
}
//
int checkDylibs(void)
{
    uint32_t count = _dyld_image_count();
    for (uint32_t i = 0 ; i < count; ++i) {
        NSString *name = [[NSString alloc]initWithUTF8String:_dyld_get_image_name(i)];
        NSLog(@"--%@", name);
        if ([name isEqualToString :@"/Library/MobileSubstrate/MobileSubstrate.dylib"]) {
            return 1;
        }
    }
    return 0;
}
//6.检查环境变量
int printEnv(void)
{
    char *c = getenv("DYLD_INSERT_LIBRARIES") ;
    NSString *string_content = [[NSString alloc] initWithCString:(const char*)c
                                encoding:NSASCIIStringEncoding];
    if ([string_content rangeOfString:@"MobileSubstrate"].location != NSNotFound) {
        return 1;
    }
    return 0;
}
//是否越狱
+(BOOL)isJK{
    BOOL isJK = NO;
    //1.使用NSFileManager判断设备是否安装了如下越狱常用工具
    if (!isJK) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:@"/Applications/Cydia.app"]){
            isJK = YES;
        }
    }
    //2.尝试打开cydia应用注册的URL scheme
    if (!isJK) {//TODO:新的系统失效
        if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://package/com.example.package"]]){
            isJK = YES;
        }
    }
    //3.尝试读取下应用列表，看看有无权限获取
    if (!isJK) {//TODO:新的系统失效
        if ([[NSFileManager defaultManager] fileExistsAtPath:@"/User/Applications/"]){
            NSArray *applist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/User/Applications/"
                                                                                   error:nil];
            NSLog(@"applist = %@",applist);
            isJK = YES;
        }
    }
    //4.使用stat系列函数检测Cydia等工具
    if (!isJK) {
        if (checkCydia()) {
            isJK = YES;
        }
    }
    //5.看看stat是不是出自系统库，有没有被攻击者换掉
    if (!isJK) {//代码编译不通过～
        if (checkInject()) {
            isJK = YES;
        }
    }
    //6.检查环境变量
    if (!isJK) {
        if (printEnv()) {
            isJK = YES;
        }
    }
    //7.看动态库
    if (!isJK) {
        if (checkDylibs()) {
            isJK = YES;
        }
    }
    //8.
    return isJK;
}

+(NSString *)getShortVersionString{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

+(NSString *)getBuildVersionString{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}

+(int)getRandomNumber:(int)from to:(int)to

{
    return (int)(from + (arc4random() % (to - from + 1)));
}

+(void)GCD_delay:(CGFloat)t b:(void(^)(void))block{
    //设置时间为2
    double delayInSeconds = t;
    //创建一个调度时间,相对于默认时钟或修改现有的调度时间。
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    //推迟两纳秒执行
    dispatch_after(delayInNanoSeconds, dispatch_get_main_queue(), [block copy]);
}

//四舍五入
+(NSString *)notRounding:(float)price afterPoint:(int)position{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [NSString stringWithFormat:@"%@",roundedOunces];
}

+(float)notRoundingFloat:(float)price afterPoint:(int)position{
    return [WJCommonUtils notRounding:price afterPoint:position].floatValue;
}

//+(CGFloat)changeScreenWidthIfVerticalScreen:(CGFloat w){
//
//    
//    
//}

+(BOOL)isSIMULATOR{
    BOOL bo = NO;
#if TARGET_IPHONE_SIMULATOR//模拟器
    bo =  YES;
#elif TARGET_OS_IPHONE//真机
    bo =  NO;
#endif
    return bo;
}


//键盘是否打开状态（可能不准）
+(BOOL)keyboardMaybeShow:(UIView *)view{
    //拿到这个view上面的第一响应对象
    if (view.isFirstResponder)
    {
        [view resignFirstResponder];
        return YES;
    }
    for (UIView* subView in view.subviews)
    {
        if ( [WJCommonUtils keyboardMaybeShow:subView])
            return YES;
    }
    return NO;
}


/**
 十进制转换为二进制
 
 @param decimal 十进制数
 @return 二进制数
 */
+ (NSString *)getBinaryByDecimal:(NSInteger)decimal {
    NSString *binary = @"";
    while (decimal) {
        binary = [[NSString stringWithFormat:@"%d", (int)(decimal % 2)] stringByAppendingString:binary];
        if (decimal / 2 < 1) {
            
            break;
        }
        decimal = decimal / 2 ;
    }
    if (binary.length % 4 != 0) {
        
        NSMutableString *mStr = [[NSMutableString alloc]init];;
        for (int i = 0; i < 4 - binary.length % 4; i++) {
            
            [mStr appendString:@"0"];
        }
        binary = [mStr stringByAppendingString:binary];
    }
    return binary;
}

+(NSArray *)getScanTypes{
//    return @[AVMetadataObjectTypeQRCode,                                                                             AVMetadataObjectTypeEAN13Code,                                                                             AVMetadataObjectTypeEAN8Code,                                                                             AVMetadataObjectTypeUPCECode,                                                                             AVMetadataObjectTypeCode39Code,                                                                             AVMetadataObjectTypeCode39Mod43Code,                                                                             AVMetadataObjectTypeCode93Code,                                                                             AVMetadataObjectTypeCode128Code,                                                                             AVMetadataObjectTypePDF417Code];
    
    return @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
   
//
//     return @[AVMetadataObjectTypeEAN13Code];
//    return @[AVMetadataObjectTypeEAN8Code];
//    return @[AVMetadataObjectTypeUPCECode];
//     return @[AVMetadataObjectTypeCode39Code];
    
    
//    return @[                                                                                                                                                                                                                                                                                                              AVMetadataObjectTypeCode128Code];
    //
    
}


+(NSString *)getLanguageName{
    NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *languageName = [appLanguages objectAtIndex:0];
    return languageName;
}




// 毛玻璃效果
+ (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
    return  [image imageByBlurRadius:10 tintColor:[UIColor colorWithWhite:1.0 alpha:0.3] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
}

+ (UIImage *)snapsHotView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size,YES,[UIScreen mainScreen].scale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



+ (UIImage *)qrImageForString:(NSString *)string imageSize:(CGFloat)Imagesize logoImageSize:(CGFloat)waterImagesize{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];//通过kvo方式给一个字符串，生成二维码
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];//设置二维码的纠错水平，越高纠错水平越高，可以污损的范围越大
    CIImage *outPutImage = [filter outputImage];//拿到二维码图片
    return [WJCommonUtils createNonInterpolatedUIImageFormCIImage:outPutImage withSize:Imagesize waterImageSize:waterImagesize];
}


+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size waterImageSize:(CGFloat)waterImagesize{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    //创建一个DeviceGray颜色空间
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    //CGBitmapContextCreate(void * _Nullable data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef  _Nullable space, uint32_t bitmapInfo)
    //width：图片宽度像素
    //height：图片高度像素
    //bitsPerComponent：每个颜色的比特值，例如在rgba-32模式下为8
    //bitmapInfo：指定的位图应该包含一个alpha通道。
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    //创建CoreGraphics image
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef); CGImageRelease(bitmapImage);
    
    //原图
    UIImage *outputImage = [UIImage imageWithCGImage:scaledImage];
    //给二维码加 logo 图
    UIGraphicsBeginImageContextWithOptions(outputImage.size, NO, [[UIScreen mainScreen] scale]);
    [outputImage drawInRect:CGRectMake(0,0 , size, size)];
    //logo图
    UIImage *waterimage = [UIImage imageNamed:@"icon_imgApp"];
    //把logo图画到生成的二维码图片上，注意尺寸不要太大（最大不超过二维码图片的%30），太大会造成扫不出来
    [waterimage drawInRect:CGRectMake((size-waterImagesize)/2.0, (size-waterImagesize)/2.0, waterImagesize, waterImagesize)];
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
}

/**
 简单的抖动动画
 **/
+ (void)animationWithView:(UIView *)view {
    CGFloat duration = 1;
    view.transform = CGAffineTransformMakeScale(1.2, 1.2);
    [UIView animateWithDuration:duration
                          delay:0.0
         usingSpringWithDamping:0.4
          initialSpringVelocity:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                          view.transform = CGAffineTransformMakeScale(1, 1);
                     } completion:nil];
}


@end
